package cn.community.system.web.controller;

import cn.community.system.domain.Admin;
import cn.community.system.domain.Association;
import cn.community.system.domain.Member;
import cn.community.system.query.AssociationQuery;
import cn.community.system.query.QueryObject;
import cn.community.system.service.IActivityService;
import cn.community.system.service.IAssociationService;
import cn.community.system.service.IMemberVoService;
import cn.community.system.util.JsonResult;
import cn.community.system.util.UserContext;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/association")
public class AssociationController {
    @Autowired
    private IAssociationService associationService;

    @Autowired
    private IMemberVoService memberVoService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"association/list","超管-社团信息列表"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") AssociationQuery qo){
        model.addAttribute("page",associationService.query(qo));
        return "user/association/list";
    }

    @RequestMapping("/myassociation")  // 我的社团
    @RequiresPermissions(value = {"association/myassociation","社团成员-我的社团列表"},logical = Logical.OR)
    public String myassociation(Model model, @ModelAttribute("qo") AssociationQuery qo){
        model.addAttribute("page",associationService.queryMyAssos(qo));
        return "association/myassociation";
    }

    @RequestMapping("/addassociation") // 加入社团
    @RequiresPermissions(value = {"association/addassociation","社团成员-加入社团列表"},logical = Logical.OR)
    public String addassociation(Model model, @ModelAttribute("qo") AssociationQuery qo){
        model.addAttribute("page",associationService.listAsso(qo));
        return "association/addassociation";
    }

    @RequestMapping("/createassociation") // 创建社团
    @RequiresPermissions(value = {"association/createassociation","社团成员-创建社团列表"},logical = Logical.OR)
    public String createassociation(Model model, @ModelAttribute("qo") AssociationQuery qo){
        model.addAttribute("page",associationService.getFounderByDutyId(qo));
        return "association/createassociation";
    }

    @RequestMapping("/inputCreate")
    @RequiresPermissions(value = {"association/inputCreate","社团成员-创建社团新增页面"},logical = Logical.OR)
    public String inputCreate(){
        return "association/input";
    }

    @RequestMapping("/save")
    @ResponseBody
    @RequiresPermissions(value = {"association/save","社团成员-社团信息新增/编辑功能"},logical = Logical.OR)
    public Object save(Association association){
        associationService.save2(association);
        return JsonResult.success();
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"association/input","社团-社团信息新增/编辑页面"},logical = Logical.OR)
    public String input(Model model,Long id){
        if(id!=null){ //编辑
            Association association = associationService.get(id);
            model.addAttribute("association",association);
        }
        return "user/association/input";
    }

    @RequestMapping("/profile")  // 个人中心
    @RequiresPermissions(value = {"association/profile","社团-个人中心页面"},logical = Logical.OR)
    public String profile(Model model){
        Association association = UserContext.getCurrentAssociation();
        model.addAttribute("association",associationService.get(association.getId()));
        return "profile/profileAssociation";
    }

    @RequestMapping("/update")  // 个人中心修改
    @RequiresPermissions(value = {"association/update","社团-个人中心编辑"},logical = Logical.OR)
    @ResponseBody
    public Object update(Association association){
        if(association.getId() != null){ // 代表修改
            associationService.myUpdate(association);
        }
        return JsonResult.success();
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"association/saveOrUpdate","社团信息新增/编辑功能"},logical = Logical.OR)
    public Object saveOrUpdate(Association association){
        if(association.getId() == null){ // 代表新增
            associationService.save(association);
        }else { // 代表修改
            associationService.update(association);
        }
        return JsonResult.success();
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    @RequiresPermissions(value = {"association/batchDelete","社团信息批量删除"},logical = Logical.OR)
    public JsonResult batchDelete(Long[] ids){
        associationService.batchDelete(ids);
        return JsonResult.success();
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"association/delete","社团信息删除"},logical = Logical.OR)
    public JsonResult delete(Long id){
        associationService.delete(id);
        return JsonResult.success();
    }

    // 审核
    @RequestMapping("/passOne")
    @ResponseBody
    @RequiresPermissions(value = {"association/passOne","社团信息审核"},logical = Logical.OR)
    public JsonResult passOne(Integer hot,Long id){
        associationService.passOne(id,hot);
        return JsonResult.success();
    }

    // 申请加入社团
    @RequestMapping("/apply")
    @ResponseBody
    @RequiresPermissions(value = {"association/apply","社团成员-申请加入社团"},logical = Logical.OR)
    public JsonResult apply(Integer hot,Long id){
        memberVoService.apply(id,hot);
        return JsonResult.success();
    }

    @RequestMapping("/listAsso")
    @ResponseBody
    public Object listAsso(){
        List<Association> associations = associationService.listAll();
        return JsonResult.success(associations);
    }


    @RequestMapping("/getSynopsisById")
    @ResponseBody
    public Object getSynopsisById(Long id){
        return JsonResult.success(associationService.get(id).getSynopsis());
    }

    @RequestMapping("/getRemarksById")
    @ResponseBody
    public Object getRemarksById(Long id){
        System.out.println(associationService.get(id).getRemarks());
        return JsonResult.success(associationService.get(id).getRemarks());
    }

    @RequestMapping("/importXls")
    @ResponseBody
    @RequiresPermissions(value = {"association/importXls","社团信息Excel导入"},logical = Logical.OR)
    public JsonResult importXls(MultipartFile file) throws Exception {
        associationService.importXls(file);
        return JsonResult.success();
    }

    @RequestMapping("/exportXls")
    @RequiresPermissions(value = {"association/importXls","社团信息Excel导出"},logical = Logical.OR)
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头
        response.setHeader("Remarks-Disposition","attachment;filename=association.xls");
        //直接使用poi
        //创建excel文件
        Workbook wb = associationService.exportXls();
        //把excel的数据输出给浏览器
        wb.write(response.getOutputStream());
    }

    /**
     * 用户远程访问用户名是否存在
     * 返回 Map true 代表验证通过（用户名不存在），false 代表 验证不通过（用户名存在）
     * @param username
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(@RequestParam("username") String username){
        Association association = associationService.getAssociationByUsername(username);
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("valid",association==null);
        return map;
    }

    /**
     * 手机号远程验证是否存在
     * 返回 Map true 代表验证通过（不存在），false 代表 验证不通过（存在）
     */
    @RequestMapping("/checkPhone")
    @ResponseBody
    public Map<String,Boolean> checkName(@RequestParam("dutyMobile")String dutyMobile, Long id){   // valid：true(插件要求的（remote.php 可以看到）)
        // 判断新增（id==null）还是编辑
        HashMap<String, Boolean> map = new HashMap<>();
        if(id == null){
            boolean checkPhone = associationService.checkPhone(dutyMobile);// true 存在
            map.put("valid",!checkPhone);
        }else {
            // 根据 id 查询手机号码
            String oldTel = associationService.get(id).getDutyMobile();
            if(oldTel == dutyMobile){  // 判断手机号有没有改变
                map.put("valid",true);
            }else {
                // 判断现在的手机号码是不是存在数据库
                map.put("valid",!associationService.checkPhone(dutyMobile));
            }
        }
        return map;
    }

    @RequestMapping("/imgUrl")
    @ResponseBody
    public JsonResult imgUrl(){
        Association association = UserContext.getCurrentAssociation();
        String imgUrl = associationService.get(association.getId()).getImgUrl();
        return JsonResult.success(imgUrl);
    }

}
